<template>
  <div class="app-container">
    <!-- 搜索区域（卡片化布局） -->
    <div class="search-card" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="微信ID" prop="wechatId">
          <el-input
            v-model="queryParams.wechatId"
            placeholder="请输入微信ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input
            v-model="queryParams.nickname"
            placeholder="请输入用户昵称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="queryParams.realName"
            placeholder="请输入真实姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input
            v-model="queryParams.idNumber"
            placeholder="请输入身份证号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入联系电话"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="入学年份" prop="enrollmentYear">
          <el-input
            v-model="queryParams.enrollmentYear"
            placeholder="请输入入学年份"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-select v-model="queryParams.college" placeholder="请选择学院" clearable>
            <el-option
              v-for="dict in dict.type.app_users_college"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-select v-model="queryParams.major" placeholder="请选择专业" clearable>
            <el-option
              v-for="dict in dict.type.app_users_major"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="idStatus">
          <el-select v-model="queryParams.idStatus" placeholder="请选择审核状态" clearable>
            <el-option
              v-for="dict in dict.type.app_id_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="校友卡卡号" prop="alumniCardNumber">
          <el-input
            v-model="queryParams.alumniCardNumber"
            placeholder="请输入校友卡卡号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable
                          v-model="queryParams.createdTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="校友卡认证时间" prop="certificationTime">
          <el-date-picker clearable
                          v-model="queryParams.certificationTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择校友卡认证时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedTime">
          <el-date-picker clearable
                          v-model="queryParams.updatedTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:users:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:users:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:users:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:users:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格区域（卡片化+样式优化） -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="usersList"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
        :cell-style="{ padding: '12px 0' }"
        :header-cell-style="{ background: '#e6f7ff', color: '#333', padding: '14px 0', fontWeight: '500' }"
        border
        stripe
        :highlight-current-row="true"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户ID" align="center" prop="userId" width="80" />
        <el-table-column label="用户头像" align="center" prop="image" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.image" :width="50" :height="50" style="border-radius: 4px; object-fit: cover;" />
          </template>
        </el-table-column>
        <el-table-column label="微信ID" align="center" prop="wechatId" width="140" />
        <el-table-column label="用户昵称" align="center" prop="nickname" width="120" />
        <el-table-column label="真实姓名" align="center" prop="realName" width="100" />
        <el-table-column label="性别" align="center" prop="gender" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.gender"/>
          </template>
        </el-table-column>
        <el-table-column label="身份证照片正面" align="center" prop="idCardFront" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.idCardFront" :width="50" :height="50" style="border-radius: 4px; object-fit: cover;" />
          </template>
        </el-table-column>
        <el-table-column label="身份证照片反面" align="center" prop="idCardBack" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.idCardBack" :width="50" :height="50" style="border-radius: 4px; object-fit: cover;" />
          </template>
        </el-table-column>
        <el-table-column label="身份证号" align="center" prop="idNumber" width="180" />
        <el-table-column label="联系电话" align="center" prop="phone" width="120" />
        <el-table-column label="入学年份" align="center" prop="enrollmentYear" width="100" />
        <el-table-column label="学院" align="center" prop="college" width="120">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.app_users_college" :value="scope.row.college"/>
          </template>
        </el-table-column>
        <el-table-column label="专业" align="center" prop="major" width="120">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.app_users_major" :value="scope.row.major"/>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="idStatus" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.app_id_status" :value="scope.row.idStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="校友卡卡号" align="center" prop="alumniCardNumber" width="120" />
        <el-table-column label="创建时间" align="center" prop="createdTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="认证时间" align="center" prop="certificationTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.certificationTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updatedTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:users:edit']"
              class="operate-btn edit-btn"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:users:remove']"
              class="operate-btn delete-btn"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        class="pagination-container"
      />
    </div>

    <!-- 添加或修改用户对话框（样式优化） -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
      class="custom-users-dialog"
      id="users-edit-dialog"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dialog-form">
        <el-form-item label="用户头像" prop="image">
          <image-upload v-model="form.image" :limit="1" :file-list="imageFileList" @change="handleImageChange"/>
        </el-form-item>
        <el-form-item label="微信ID" prop="wechatId">
          <el-input v-model="form.wechatId" placeholder="请输入微信ID" class="form-input" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入用户昵称" class="form-input" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" class="form-input" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别" class="form-input">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证照片正面" prop="idCardFront">
          <image-upload v-model="form.idCardFront" :limit="1" :file-list="idFrontFileList" @change="handleIdFrontChange"/>
        </el-form-item>
        <el-form-item label="身份证照片反面" prop="idCardBack">
          <image-upload v-model="form.idCardBack" :limit="1" :file-list="idBackFileList" @change="handleIdBackChange"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入身份证号" class="form-input" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" class="form-input" />
        </el-form-item>
        <el-form-item label="入学年份" prop="enrollmentYear">
          <el-input v-model="form.enrollmentYear" placeholder="请输入入学年份" class="form-input" />
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-select v-model="form.college" placeholder="请选择学院" class="form-input">
            <el-option
              v-for="dict in dict.type.app_users_college"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-select v-model="form.major" placeholder="请选择专业" class="form-input">
            <el-option
              v-for="dict in dict.type.app_users_major"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="idStatus">
          <el-radio-group v-model="form.idStatus" class="radio-group">
            <el-radio
              v-for="dict in dict.type.app_id_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              class="radio-item"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="校友卡卡号" prop="alumniCardNumber">
          <el-input v-model="form.alumniCardNumber" placeholder="请输入校友卡卡号" class="form-input" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable
                          v-model="form.createdTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择创建时间"
                          class="form-input">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="校友卡认证时间" prop="certificationTime">
          <el-date-picker clearable
                          v-model="form.certificationTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择校友卡认证时间"
                          class="form-input">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedTime">
          <el-date-picker clearable
                          v-model="form.updatedTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择更新时间"
                          class="form-input">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUsers, getUsers, delUsers, addUsers, updateUsers } from "@/api/system/users"

export default {
  name: "Users",
  dicts: ['app_id_status', 'app_users_college', 'app_users_major', 'sys_user_sex'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      usersList: [],
      title: "",
      open: false,
      // 图片上传文件列表（优化上传体验）
      imageFileList: [],
      idFrontFileList: [],
      idBackFileList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        image: null,
        wechatId: null,
        nickname: null,
        realName: null,
        gender: null,
        idCardFront: null,
        idCardBack: null,
        idNumber: null,
        phone: null,
        enrollmentYear: null,
        college: null,
        major: null,
        idStatus: null,
        alumniCardNumber: null,
        createdTime: null,
        certificationTime: null,
        updatedTime: null
      },
      form: {},
      rules: {
        wechatId: [
          { required: true, message: "微信ID不能为空", trigger: "blur" }
        ],
        nickname: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        realName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" }
        ],
        idCardFront: [
          { required: true, message: "身份证照片正面不能为空", trigger: "blur" }
        ],
        idCardBack: [
          { required: true, message: "身份证照片反面不能为空", trigger: "blur" }
        ],
        idNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { min: 15, max: 18, message: "身份证号长度为15-18位", trigger: "blur" }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号格式", trigger: "blur" }
        ],
        enrollmentYear: [
          { pattern: /^\d{4}$/, message: "请输入4位数字的入学年份", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取用户列表
    getList() {
      this.loading = true
      listUsers(this.queryParams).then(response => {
        this.usersList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消操作
    cancel() {
      this.open = false
      this.reset()
    },
    // 重置表单
    reset() {
      this.form = {
        userId: null,
        image: null,
        wechatId: null,
        nickname: null,
        realName: null,
        gender: null,
        idCardFront: null,
        idCardBack: null,
        idNumber: null,
        phone: null,
        enrollmentYear: null,
        college: null,
        major: null,
        idStatus: null,
        alumniCardNumber: null,
        createdTime: null,
        certificationTime: null,
        updatedTime: null
      }
      // 重置图片上传列表
      this.imageFileList = []
      this.idFrontFileList = []
      this.idBackFileList = []
      this.resetForm("form")
    },
    // 搜索查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置查询
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 表格选择变更
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 新增用户
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加用户"
    },
    // 修改用户
    handleUpdate(row) {
      this.reset()
      const userId = row.userId || this.ids
      getUsers(userId).then(response => {
        this.form = response.data
        // 回显图片上传列表
        if (this.form.image) this.imageFileList = [{ url: this.form.image }]
        if (this.form.idCardFront) this.idFrontFileList = [{ url: this.form.idCardFront }]
        if (this.form.idCardBack) this.idBackFileList = [{ url: this.form.idCardBack }]
        this.open = true
        this.title = "修改用户"
      })
    },
    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateUsers(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUsers(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 删除用户
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$modal.confirm(`是否确认删除用户编号为"${userIds}"的数据项？`).then(() => {
        return delUsers(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 导出用户
    handleExport() {
      this.download('system/users/export', {
        ...this.queryParams
      }, `users_${new Date.now()}.xlsx`)
    },
    // 表格行交替色
    tableRowClassName({ rowIndex }) {
      return rowIndex % 2 === 0 ? 'row-even' : 'row-odd'
    },
    // 图片上传变更（用户头像）
    handleImageChange(fileList) {
      this.form.image = fileList.length > 0 ? fileList[0].url : null
    },
    // 图片上传变更（身份证正面）
    handleIdFrontChange(fileList) {
      this.form.idCardFront = fileList.length > 0 ? fileList[0].url : null
    },
    // 图片上传变更（身份证反面）
    handleIdBackChange(fileList) {
      this.form.idCardBack = fileList.length > 0 ? fileList[0].url : null
    },
    // 对话框关闭回调
    handleDialogClose() {
      this.reset()
    }
  }
}
</script>

<style lang="scss" scoped>
// 全局变量定义
$primary-color: #1677ff;
$light-primary: #e6f7ff;
$gray-light: #f5f7fa;
$gray-mid: #e8e8e8;
$text-main: #333333;
$text-secondary: #666666;
$border-radius: 6px;
$shadow-light: 0 2px 8px rgba(0, 0, 0, 0.08);
$shadow-normal: 0 4px 16px rgba(0, 0, 0, 0.1);

// 容器样式
.app-container {
  padding: 16px;
  background-color: $gray-light;
  min-height: 100vh;
}

// 搜索区卡片样式
.search-card {
  background-color: #fff;
  padding: 16px;
  border-radius: $border-radius;
  box-shadow: $shadow-light;
  margin-bottom: 16px;
}

// 表格卡片样式
.table-card {
  background-color: #fff;
  border-radius: $border-radius;
  box-shadow: $shadow-light;
  overflow: hidden;
  margin-bottom: 16px;

  ::v-deep .el-table {
    border: none;
    border-radius: $border-radius 0 0 0;
  }

  ::v-deep .el-table__header-wrapper {
    border-bottom: 1px solid $gray-mid;
  }

  // 表格行样式
  ::v-deep .row-even {
    background-color: #fafafa;
  }
  ::v-deep .row-odd {
    background-color: #fff;
  }
  ::v-deep .el-table__row:hover {
    background-color: $light-primary !important;
  }
}

// 分页容器样式
.pagination-container {
  padding: 16px;
  text-align: right;
  border-top: 1px solid $gray-mid;
}

// 操作按钮样式
.operate-btn {
  transition: all 0.2s;
  margin: 0 4px;

  &:hover {
    opacity: 0.8;
    transform: scale(1.05);
  }
}
.edit-btn {
  color: $primary-color;
}
.delete-btn {
  color: #ff4d4f;
}

// 对话框样式
::v-deep #users-edit-dialog {
  width: 1000px !important;
  max-width: 95% !important;
  min-width: 800px !important;

  .el-dialog__header {
    background-color: $light-primary;
    border-bottom: 1px solid $gray-mid;
    border-radius: $border-radius $border-radius 0 0;
    padding: 14px 20px;
  }

  .el-dialog__title {
    color: $text-main;
    font-size: 16px;
    font-weight: 500;
  }

  .el-dialog__body {
    padding: 20px;
    max-height: 60vh;
    overflow-y: auto;
  }

  .el-dialog__footer {
    padding: 12px 20px;
    border-top: 1px solid $gray-mid;
    text-align: right;
  }
}

// 对话框表单样式
.dialog-form {
  ::v-deep .el-form-item {
    margin-bottom: 16px;
    display: flex;
    align-items: flex-start; // 标签换行时，顶部对齐
  }

  ::v-deep .el-form-item__label {
    text-align: right !important;
    padding-right: 15px !important;
    width: 120px !important;
    color: $text-secondary;
    font-size: 18px;
    white-space: normal; // 允许文字换行
    line-height: 1.5; // 换行后行高舒适
    flex-shrink: 0; // 禁止标签宽度收缩，保持固定宽
  }

  ::v-deep .el-form-item__content {
    flex: 1 !important;
    margin-left: 0 !important;
  }
}

// 表单输入框样式
.form-input {
  width: 100%;
  border-radius: 4px;
  border-color: $gray-mid;
  transition: all 0.2s;

  ::v-deep input,
  ::v-deep .el-select__wrapper {
    border-radius: 4px;
  }

  &:focus-within {
    border-color: $primary-color;
    box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.1);
  }
}

// 单选组样式
.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;

  .radio-item {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

// 图片上传预览样式
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  border-radius: 4px;
  overflow: hidden;
}

// 响应式适配
@media (max-width: 1440px) {
  // 搜索项自动换行
  ::v-deep .el-form--inline {
    flex-wrap: wrap;
  }
  ::v-deep .el-form--inline .el-form-item {
    flex: 1 1 auto;
    min-width: 200px;
  }

  // 表格列宽适配
  ::v-deep .el-table {
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  ::v-deep #users-edit-dialog {
    width: 95% !important;
  }

  ::v-deep #users-edit-dialog .el-form-item__label {
    width: 100px !important;
  }

  // 表格操作列调整
  ::v-deep .fixed-width {
    width: 100px !important;
  }
}
</style>
